'use client';

import { useState, useEffect } from 'react';
import { Alert, Snackbar, CircularProgress } from '@mui/material';
import { useRouter } from 'next/navigation';
import { examApi } from '@/api/exams';
import ExamForm from '@/components/ExamForm';
import dayjs from 'dayjs';

export default function EditExamPage({ params }: { params: { id: string } }) {
  const [loading, setLoading] = useState(false);
  const [initializing, setInitializing] = useState(true);
  const [initialValues, setInitialValues] = useState(null);
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' });
  const router = useRouter();

  useEffect(() => {
    const fetchExam = async () => {
      try {
        const exam = await examApi.getById(Number(params.id));
        setInitialValues({
          title: exam.title,
          subject: exam.subject,
          description: exam.description,
          examTime: [dayjs(exam.startTime), dayjs(exam.endTime)],
          duration: exam.duration,
          totalScore: exam.totalScore,
          passingScore: exam.passingScore,
        });
      } catch (error) {
        setSnackbar({ open: true, message: '获取考试信息失败', severity: 'error' });
        router.push('/exams');
      } finally {
        setInitializing(false);
      }
    };

    fetchExam();
  }, [params.id, router]);

  const onFinish = async (values: any) => {
    try {
      setLoading(true);
      const [startTime, endTime] = values.examTime;
      const examData = {
        ...values,
        startTime: startTime.toDate(),
        endTime: endTime.toDate(),
        examTime: undefined,
      };
      await examApi.update(Number(params.id), examData);
      setSnackbar({ open: true, message: '更新成功', severity: 'success' });
      router.push('/exams');
    } catch (error) {
      setSnackbar({ open: true, message: '更新失败', severity: 'error' });
    } finally {
      setLoading(false);
    }
  };

  if (initializing) {
    return (
      <div className="flex justify-center items-center h-screen">
        <CircularProgress size={60} />
      </div>
    );
  }

  if (!initialValues) {
    return null;
  }

  return (
    <div className="p-6">
      <div className="mb-4">
        <h1 className="text-2xl font-bold">编辑考试</h1>
      </div>
      <ExamForm
        initialValues={initialValues}
        onFinish={onFinish}
        loading={loading}
        submitText="保存修改"
      />
      <Snackbar
        open={snackbar.open}
        autoHideDuration={3000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert severity={snackbar.severity as any} sx={{ width: '100%' }}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </div>
  );
}